﻿
using AlchemyAPIClient;
using AlchemyAPIClient.Requests;
using Eyskens.AutoTaggerWeb.Helpers;
using Eyskens.AutoTaggerWeb.Models;
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace Eyskens.AutoTaggerWeb.Controllers
{
    public class ExtractInfoAlchemyController : Controller
    {
        // GET: ExtractInfoAlchemy
        public async Task<ActionResult> Index()
        {
            AlchemyEntitiesResponseModel model = new AlchemyEntitiesResponseModel();
            var TokenList = new List<TokenInfo>();
            AppWebHelper hlp = new AppWebHelper(HttpContext.Request.QueryString[Constants.SPAppWebUrl] as string);
            List<GlobalSetting> gs = hlp.GetGlobalSettings();
            var AlchemyAPIKey = gs.Where(s => s.key == Constants.AlchemyAPIKey).SingleOrDefault();
            
            if (AlchemyAPIKey != null && !string.IsNullOrEmpty(AlchemyAPIKey.value))
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                using (var ctx = spContext.CreateUserClientContextForSPHost())
                {
                    LogHelper.Log("ctx is null " + (ctx == null));
                    ListItem DocumentItem = null;
                    string FileContent = FileHelper.GetFileContent(
                        ctx,
                        new Guid(HttpContext.Request.QueryString["SPListId"]),
                        Convert.ToInt32(HttpContext.Request.QueryString["SPListItemId"]),
                        out DocumentItem);

                    Dictionary<string, int> tokens = AutoTaggingHelper.Tokenize(FileContent);
                    var SortedTokens = tokens.OrderByDescending(x => x.Value);

                    foreach (var token in SortedTokens)
                    {
                        TokenList.Add(new TokenInfo
                        {
                            word=token.Key.Replace("\r\n","").Replace("\n",""),
                            count = token.Value
                        });
                    }
                    
                    model.tokens = (from word in TokenList
                             where word.word.Length >= 3
                             orderby word.count descending
                             select word).Take(50).Where(w => !AutoTaggingHelper.IsEmptyWord(
                            w.word.ToLowerInvariant(), AutoTaggingHelper.LanguageIdentifier.Identify(FileContent).FirstOrDefault().Item1.Iso639_3, hlp)).Take(10);

                    
                    var AlchemyEndPointUrl = gs.Where(s => s.key == Constants.AlchemyEndPointUrl).SingleOrDefault();
                    string endp="https://access.alchemyapi.com/calls/";
                    if(AlchemyEndPointUrl != null && !String.IsNullOrEmpty(AlchemyEndPointUrl.value))
                    {
                        endp = AlchemyEndPointUrl.value;
                    }
                    AlchemyClient cli = new AlchemyClient(AlchemyAPIKey.value, endp);
                    AlchemyTextEntitiesRequest entities = new AlchemyTextEntitiesRequest(FileContent, cli);
                    model.entities = await entities.GetResponse();
                    AlchemyTextConceptsRequest concepts = new AlchemyTextConceptsRequest(FileContent, cli);
                    model.concepts = await concepts.GetResponse();
                    AlchemyTextSentimentRequest sentiment = new AlchemyTextSentimentRequest(FileContent, cli);
                    model.sentiment = await sentiment.GetResponse();
                }
                
            }
            else
            {
                model.ProcessStatus = "No Alchemy API key could be found";
            }
            return View(model);
        }
    }
}